<template>
  <div>
    <div class="container mg-t-20">
      <el-row>
        <el-col :span="24">
          <div class="user-head border-radius box-shadow border-gray">
            <img class="user-head-bg" src="@/static/image/user_bg.svg">
            <client-only>
              <el-skeleton :animated="true" :loading="user_loading" :rows="0" :throttle="200">
                <template slot="template">
                  <div class="user-avatar">
                    <el-skeleton-item variant="p" style="width: 100px; height: 100px; border-radius: 100%" />
                  </div>
                  <div class="user-name fs-18">
                    <h1><el-skeleton-item variant="p" style="width: 100%; height: 20px" /></h1>
                  </div>
                  <div class="fs-14 f-gray-color">
                    <h1><el-skeleton-item variant="p" style="width: 100%; height: 20px; margin-top: 10px" /></h1>
                  </div>
                </template>
                <template>
                  <div class="user-avatar" @click="avatarOpen">
                    <div :class="{'user-avatar-active':isSelf }">
                      <el-avatar style="font-size: 50px;" icon="el-icon-user-solid" :size="100" :src="imgPrefix + userInfo.avatar" :key="imgPrefix + userInfo.avatar"></el-avatar>
                    </div>
                  </div>
                  <div class="user-name fs-18">
                    <h1>{{ userInfo.nickName }}</h1>
                  </div>
                  <div class="fs-14 mg-t-20 f-gray-color" v-if="userInfo.createTime != null">
                    <h1>注册时间：{{ userInfo.createTime }}（{{ (userInfo.createTime == null) ? '':$utils_formatTime.timeStr(userInfo.createTime) }}）</h1>
                  </div>
                </template>
              </el-skeleton>
            </client-only>
          </div>
        </el-col>
        <el-col :span="24">
          <div class="user-body">
            <el-tabs class="user-navbar bg-white border-gray box-shadow border-radius" v-model="activeName" :tabPosition="align">
              <el-tab-pane :label="isSelf ? '我的评论':'TA的评论'" name="comments">
                <el-card :body-style="{padding: '15px'}" class="border-radius" style="border: none">
                  <Comments v-if="isComments" :username="userInfo.userName" :isComments="false" :isUser="true" />
                </el-card>
              </el-tab-pane>
              <el-tab-pane :label="isSelf ? '我的收藏':'TA的收藏'" name="collection">
                <el-card :body-style="{padding: '25px 15px 15px 15px'}" class="border-radius" style="border: none">
                  <Links :isShowSubmit="false" :userId="Number(id)" :isPage="true" :listSize="16"/>
                </el-card>
              </el-tab-pane>
              <el-tab-pane label="基础信息" name="info">
                <el-card :body-style="{padding: '15px'}" class="border-radius" style="border: none" v-if="isSelf">
                  <el-form :model="userInfoForm" ref="userInfoForm" :rules="userInfoFormRules" label-width="80px">
                    <el-form-item>
                      <AvatarUpload :size="100" ref="avatarUpload" @imgUrl="getImgUrl"></AvatarUpload>
                    </el-form-item>
                    <el-form-item label="用户名">
                      <el-input type="text" v-model="userInfoForm.userName" :disabled="true" size="medium"></el-input>
                    </el-form-item>
                    <el-form-item label="用户昵称" prop="nickName">
                      <el-input type="text" placeholder="请输入用户昵称" v-model="userInfoForm.nickName" size="medium"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号码" prop="phonenumber">
                      <el-input type="text" placeholder="请输入手机号码" v-model="userInfoForm.phonenumber" size="medium"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱号" prop="email">
                      <el-input type="text" placeholder="请再输入邮箱号" v-model="userInfoForm.email" :disabled="true" size="medium"></el-input>
                    </el-form-item>
                    <el-form-item label="选择性别" prop="sex">
                      <el-radio-group v-model="userInfoForm.sex">
                        <el-radio label="1">男</el-radio>
                        <el-radio label="2">女</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="密钥" prop="keyNumber">
                      <el-input type="text" placeholder="请再输入邮箱号" v-model="userInfoForm.keyNumber" size="medium" :disabled="true">
                        <el-button slot="append" icon="el-icon-refresh" @click="generateKey" :loading="generateKeyLoading">一键生成</el-button>
                      </el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" size="small" @click="userInfoFormSubmit" :loading="userInfoLoading">保存</el-button>
                    </el-form-item>
                  </el-form>
                </el-card>
                <el-card :body-style="{padding: '15px'}" class="border-radius" style="border: none" v-else>
                  <el-descriptions class="mg-t-10" title="用户信息" :column="descriptionsColumn" size="medium" border>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-user"></i>
                        用户名
                      </template>
                      {{ userInfo.userName }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-user"></i>
                        用户昵称
                      </template>
                      {{ userInfo.nickName }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-mobile-phone"></i>
                        手机号码
                      </template>
                      {{ userInfo.phonenumber }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-message"></i>
                        邮箱
                      </template>
                      {{ userInfo.email }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-male" v-if="userInfo.sex === '1'"></i>
                        <i class="el-icon-female" v-else></i>
                        性别
                      </template>
                      <el-tag size="small" v-if="userInfo.sex === '1'">男</el-tag>
                      <el-tag size="danger" v-else>女</el-tag>
                    </el-descriptions-item>
                  </el-descriptions>
                </el-card>
              </el-tab-pane>
              <el-tab-pane label="安全设置" name="security" v-if="isSelf">
                <el-card :body-style="{padding: '15px'}" class="border-radius" style="border: none">
                  <el-row class="fs-14 text-center">
                    <el-col :span="24">
                      <el-row class="security-item border-bottom" type="flex" align="middle" style="flex-wrap: wrap;">
                        <el-col :xs="24" :sm="24" :md="2" :lg="2">
                          登录密码
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="20" :lg="20">
                          已设置。密码长度在 6 到 20 个字符。
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="2" :lg="2">
                          <el-button @click="resetPwd_dialogVisible = true" type="primary" plain size="mini">修改</el-button>
                        </el-col>
                      </el-row>
                    </el-col>
                    <el-col :span="24">
                      <el-row class="security-item border-bottom" type="flex" align="middle" style="flex-wrap: wrap;">
                        <el-col :xs="24" :sm="24" :md="2" :lg="2">
                          安全邮箱
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="20" :lg="20" v-if="resetEmailType === 1">
                          您已设置邮箱：{{ userInfo.email }}，邮箱可以用来登录、找回密码、接收通知等。
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="20" :lg="20" v-if="resetEmailType === 2">
                          您暂未设置邮箱，绑定邮箱可以用来登录、找回密码、接收通知等。
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="2" :lg="2">
                          <el-button @click="resetEmail_dialogVisible = true;resetEmailType = 1" v-if="resetEmailType === 1" type="primary" plain size="mini">修改</el-button>
                          <el-button @click="resetEmail_dialogVisible = true;resetEmailType = 2" v-if="resetEmailType === 2" type="warning" plain size="mini">绑定</el-button>
                        </el-col>
                      </el-row>
                    </el-col>
                  </el-row>
                </el-card>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-col>
      </el-row>
    </div>

    <!--修改密码-->
    <el-dialog
      title="修改密码"
      :visible.sync="resetPwd_dialogVisible"
      width="30%">
      <el-form :model="resetPwdFrom" ref="resetPwdFrom" :rules="resetPwdFromRules">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="resetPwdFrom.oldPassword" placeholder="请输入旧密码" type="password" show-password size="medium"/>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPwdFrom.newPassword" placeholder="请输入新密码" type="password" show-password size="medium"/>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPwdFrom.confirmPassword" placeholder="请确认新密码" type="password" show-password @keyup.enter.native="resetPwdFromSubmit" size="medium"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resetPwdFromSubmit">保存</el-button>
      </span>
    </el-dialog>

    <!--操作邮箱-->
    <el-dialog
      :title="((resetEmailType === 1) ? '修改邮箱' : '绑定邮箱')"
      :visible.sync="resetEmail_dialogVisible"
      width="30%">
      <template v-if="resetEmailType === 1"><!--修改-->
        <el-form :model="resetEmailFrom" ref="ruleForm" :rules="resetEmailFromRules">
          <el-form-item prop="oldEmail">
            <el-input type="text" placeholder="请输入旧邮箱地址" :value="resetEmailFrom.oldEmail" size="medium"></el-input>
          </el-form-item>
          <el-form-item prop="codeEmail">
            <el-input placeholder="请输入验证码" :value="resetEmailFrom.codeEmail" size="medium">
              <div slot="append">
                <el-button type="primary">获取验证码</el-button>
              </div>
            </el-input>
          </el-form-item>
          <el-form-item prop="newEmail" :value="resetEmailFrom.newEmail">
            <el-input type="text" placeholder="请输入新邮箱地址" size="medium"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template v-if="resetEmailType === 2"><!--绑定-->
        <el-form :model="resetEmailFrom" ref="ruleForm" :rules="resetEmailFromRules">
          <el-form-item prop="newEmail" :value="resetEmailFrom.newEmail">
            <el-input type="text" placeholder="请输入新邮箱地址" size="medium"></el-input>
          </el-form-item>
          <el-form-item prop="codeEmail">
            <el-input placeholder="请输入验证码" :value="resetEmailFrom.codeEmail" size="medium">
              <div slot="append">
                <el-button type="primary">获取验证码</el-button>
              </div>
            </el-input>
          </el-form-item>
        </el-form>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resetEmailFromSubmit">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {mapMutations, mapState} from "vuex";

export default {
  layout: 'navigation',
  computed: {
    ...mapState({
      s_userInfo: state => state.user.userInfo,
      nav_config: state => state.config
    })
  },
  //SEO优化
  head(){
    return{
      title: "个人中心" + this.nav_config.separate + this.nav_config.name,
      meta: [
        { name: 'keywords', content: this.nav_config.keywords },
        { hid: 'description', name: 'description', content: this.nav_config.description },
      ]
    }
  },
  data(){
    const equalToPassword = (rule, value, callback) => {
      if (this.resetPwdFrom.newPassword !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return{
      //左侧导航对齐方式
      align: 'left',
      //图片链接前缀
      imgPrefix: process.env.NUXT_APP_BASE_API,
      id: null,
      //标签页选中的值
      activeName: "comments",
      //动态加载
      user_loading: true,
      //用户信息
      userInfo: {
        avatar: ""
      },
      //当前页面是否为用户自己的个人中心
      isSelf: false,
      //是否显示评论
      isComments: false,
      //用户信息表单
      userInfoForm: {
        userName: null,
        nickName: null,
        email: null,
        phonenumber: null,
        sex: null,
        keyNumber: null
      },
      //用户信息表单校验
      userInfoFormRules: {
        nickName: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 10, message: '昵称长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        phonenumber: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        keyNumber: [
          { required: true, message: '请输入密钥', trigger: 'blur' },
        ]
      },
      //用户信息按钮加载
      userInfoLoading: false,
      //登录的用户信息
      loginUserInfo: null,
      /** 修改密码窗口 */
      resetPwd_dialogVisible: false,
      resetPwdFrom: {
        oldPassword: undefined,
        newPassword: undefined,
        confirmPassword: undefined
      },
      resetPwdFromRules: {
        oldPassword: [
          { required: true, message: "旧密码不能为空", trigger: "blur" }
        ],
        newPassword: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ]
      },
      /** 修改密码窗口 end */
      /** 操作邮箱窗口 */
      resetEmail_dialogVisible: false,
      //修改或绑定 1修改 2绑定
      resetEmailType: 1,
      resetEmailFrom: {
        oldEmail: null, //旧邮箱
        newEmail: null, //新邮箱
        codeEmail: null //验证码
      },
      resetEmailFromRules: {
        oldEmail: [
          { required: true, message: "旧邮箱地址不能为空", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        newEmail: [
          { required: true, message: "新邮箱地址不能为空", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        codeEmail: [
          { required: true, message: "验证码不能为空", trigger: "blur" }
        ]
      },
      /** 操作邮箱窗口 end */
      //用户信息一行N个
      descriptionsColumn: 2,
      //生成密钥按钮加载
      generateKeyLoading: false,
    }
  },
  validate({ params }) {
    this.id = params.id;
    // 必须是number类型
    return /^\d+$/.test(params.id)
  },
  created(){
    this.id = this.$route.params.id;
    this.loginUserInfo = JSON.parse(JSON.stringify(this.s_userInfo));
  },
  mounted() {
    if (this.s_userInfo.userId === Number(this.id)) {
      this.isSelf = true;
      if (this.s_userInfo.email == null || this.s_userInfo.email === "") {
        this.resetEmailType = 2;
      }
    }
    this.getInfo();
    if(this.isMobileDevice()){
      this.align = "top";
      this.descriptionsColumn = 1;
    }
  },
  methods: {
    ...mapMutations({
      SET_USERINFO: 'user/SET_USERINFO'
    }),
    //判断当前设备是否为移动端
    isMobileDevice() {
      const ua = navigator.userAgent.toLowerCase();
      const t1 =
        /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mac/i.test(
          ua
        );
      const t2 =
        ua.indexOf("windows") < 0 &&
        ua.indexOf("iphone") < 0 &&
        navigator.maxTouchPoints > 1;
      return t1 || t2;
    },
    //保存用户信息
    userInfoFormSubmit(){
      this.userInfoLoading = true;
      this.$refs['userInfoForm'].validate((valid) => {
        if(valid){
          this.loginUserInfo.nickName = this.userInfoForm.nickName;
          this.loginUserInfo.sex = this.userInfoForm.sex;
          this.loginUserInfo.phonenumber = this.userInfoForm.phonenumber;
          this.$api_user.updateInfo(this.loginUserInfo).then(res => {
            if(res.code === 200){
              this.$message({
                message: '信息保存成功',
                type: 'success'
              });
              this.getLoginInfo();
              this.getInfo();
            }else{
              this.$message.error(res.msg);
            }
          });
          this.userInfoLoading = false;
        }else{
          this.$message.error("请输入正确的信息");
          this.userInfoLoading = false;
          return false;
        }
      });
    },
    //获取登录用户信息
    getLoginInfo(){
      this.$api_login.getInfo().then(response => {
        if(response.code === 200){
          this.SET_USERINFO(response.user);
        }
      });
    },
    //获取个人信息
    getInfo(){
      this.$api_user.getInfo(this.id).then(res => {
        if(res.code === 200){
          this.userInfo = res.data;
          this.user_loading = false;
          this.isComments = true;
          if (this.s_userInfo.userId === Number(this.id)) {
            this.userInfoForm.avatar = this.userInfo.avatar;
            this.userInfoForm.userName = res.data.userName;
            this.userInfoForm.nickName = res.data.nickName;
            this.userInfoForm.email = res.data.email;
            this.userInfoForm.phonenumber = res.data.phonenumber;
            this.userInfoForm.sex = res.data.sex;
            this.userInfoForm.keyNumber = res.data.keyNumber;
          }
        }else{
          this.$router.push("/error");
        }
      })
    },
    //修改密码
    resetPwdFromSubmit(){
      this.$refs.resetPwdFrom.validate(valid => {
        if (valid) {
          this.$api_user.updatePassword(this.resetPwdFrom.oldPassword, this.resetPwdFrom.newPassword).then(res => {
            if(res.code === 200){
              this.$message({
                message: '修改密码成功',
                type: 'success',
                duration: process.env.MSG_TIME
              });
              this.resetPwd_dialogVisible = false;
            }else{
              this.$message.error(res.msg);
              this.resetPwd_dialogVisible = false;
            }
            this.resetPwdFrom = {};
          })
        }else{
          this.$message.error("请输入正确的信息");
          return false;
        }
      });
    },
    //操作邮箱
    resetEmailFromSubmit(){
      this.resetEmail_dialogVisible = false;
      this.$message({
        message: "暂未开发",
        type: "warning"
      })
    },
    //获取头像
    getImgUrl(value){
      this.userInfo.avatar = value;
      console.log(value);
    },
    //上传头像
    avatarOpen(){
      if(this.isSelf){
        this.$refs['avatarUpload'].editCropper();
      }
    },
    //生成密钥
    generateKey(){
      this.generateKeyLoading = true;
      this.$api_user.generateKey().then(res => {
        if(res.code === 200){
          this.$message({
            message: '密钥成功生成',
            type: 'success',
            duration: process.env.MSG_TIME
          });
          this.userInfoForm.keyNumber = res.msg;
        }else{
          this.$message.error(res.msg);
        }
        this.generateKeyLoading = false;
      })
    }
  }
}
</script>

<style scoped>
.user-head{
  display: flex;
  align-items: flex-end;
  justify-content: center;
  flex-wrap: wrap;
  margin-bottom: 20px;
}
.user-head-bg{
  width: 100%;
  height: 300px;
  -o-object-fit: cover;
  object-fit: cover;
  border-radius: 8px 8px 0 0;
}
.user-head>div{
  text-align: center;
  margin-bottom: 20px;
}
.user-avatar{
  text-align: center;
  background-color: #FFFFFF;
  padding: 8px;
  border-radius: 100%;
  width: 100px;
  margin: -60px auto 0;
  position: relative;
}
.user-avatar-active:hover:after {
  content: '+';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  color: #eee;
  background: rgba(0, 0, 0, 0.5);
  font-size: 24px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  cursor: pointer;
  width: 100px;
  height: 100px;
  line-height: 100px;
  border-radius: 50%;
  text-align: center;
  margin: 8px;
}
.user-name{
  width: 100%;
}
.user-navbar{
  overflow: auto;
}
.security-item{
  padding: 15px 0;
}
</style>
<style>
.user-navbar .el-tabs__header{
  margin: 15px 10px !important;
}
</style>

